//
//  BIDMeetingListViewController.m
//  JuanChengOA
//
//  Created by mal on 2017/7/25.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDMeetingListViewController.h"
#import "BIDCreateMeetingViewController.h"
#import "BIDReceivedMeetingCell.h"
#import "BIDMeetingDetailViewController.h"

static NSString *receivedListURL = @"noticeAndroid!listReceiveNotice.action";

static NSString *sentListURL = @"noticeAndroid!listSendNotice.action";

//删除已收会议
static NSString *deleteReceivedMeetingURL = @"noticeAndroid!dropNoticeReply.action";
//删除已发会议
static NSString *deleteSentMeetingURL = @"noticeAndroid!dropNotice.action";

@interface BIDMeetingListViewController ()<BIDBaseListViewDelegate>
{
    //是已收列表还是已发列表
    BOOL _isSent;
    BOOL _isRegister;
}
@end

@implementation BIDMeetingListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createTitleView];
    //默认显示已收
    _isSent = NO;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(createMeeting)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.curPage = 0;
    [self.dataSourceArr removeAllObjects];
    [self loadData];
}

- (void)createTitleView
{
    UISegmentedControl *segmentedCtrl = [[UISegmentedControl alloc] initWithItems:@[@"已收会议", @"已发会议"]];
    [segmentedCtrl addTarget:self action:@selector(segmentedCtrlChangeEventHandler:) forControlEvents:UIControlEventValueChanged];
    segmentedCtrl.selectedSegmentIndex = 0;
    self.navigationItem.titleView = segmentedCtrl;
}

- (void)createMeeting
{
    BIDCreateMeetingViewController *vc = [[BIDCreateMeetingViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self setNavigationControllerAttribute:nav];
    [self presentViewController:nav animated:YES completion:^{}];
}

- (void)loadData
{
    self.curPage++;
    NSString *strRequestURL = @"";
    NSString *strPost = @"";
    if(_isSent)
    {
        //已发
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], sentListURL];
        strPost = [[NSString alloc] initWithFormat:@"notice.createUser=%@&page=%ld&rows=%ld", [AppDelegate getUserId], self.curPage, self.countPerPage];
    }
    else
    {
        //已收
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], receivedListURL];
        strPost = [[NSString alloc] initWithFormat:@"noticeReply.receiveUser=%@&page=%ld&rows=%ld", [AppDelegate getUserId], self.curPage, self.countPerPage];
    }
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            NSArray *arr = responseDic[@"rows"];
            if(!arr) return;
            [self.dataSourceArr addObjectsFromArray:arr];
            if(self.dataSourceArr.count < self.curPage*self.countPerPage)
            {
                [self.myTableView hasNoMoreData];
            }
            else
            {
                [self.myTableView hasMoreData];
            }
        }
        [self.myTableView reloadData];
    }];
}

- (void)segmentedCtrlChangeEventHandler:(UISegmentedControl *)segmentedCtrl
{
    _isSent = !_isSent;
    self.curPage = 0;
    [self.dataSourceArr removeAllObjects];
    [self loadData];
}

- (void)deleteMeetingAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = indexPath.row;
    NSDictionary *dic = self.dataSourceArr[row];
    NSString *meetingID = _isSent?dic[@"id"]:dic[@"noticeId"];
    NSString *strRequestURL = @"";
    if(_isSent)
    {
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], deleteSentMeetingURL];
    }
    else
    {
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], deleteReceivedMeetingURL];
    }
    NSString *strPost = [[NSString alloc] initWithFormat:@"selectIds=%@", meetingID];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary* responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            //删除成功
            [self.dataSourceArr removeObjectAtIndex:row];
            [self.myTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *received_identifier = @"received";
    static NSString *sent_identifier = @"sent";
    NSUInteger row = indexPath.row;
    NSDictionary *dic;
    NSDictionary *noticeDic;
    if(!_isSent)
    {
        dic = self.dataSourceArr[row];
        noticeDic = dic[@"notice"];
    }
    else
    {
        dic = self.dataSourceArr[row];
    }
    if(!_isRegister)
    {
        _isRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDReceivedMeetingCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:received_identifier];
    }
    if(_isSent)
    {
        //已发
        cell = [tableView dequeueReusableCellWithIdentifier:sent_identifier];
        if(!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:sent_identifier];
        }
        cell.textLabel.text = dic[@"title"];
        cell.textLabel.font = [UIFont systemFontOfSize:15.f];
        cell.textLabel.textColor = RGBACOLOR(50, 54, 59, 1);
        cell.detailTextLabel.text = dic[@"createTime"];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:13.f];
        cell.detailTextLabel.textColor = RGBACOLOR(71, 70, 68, 1);
    }
    else
    {
        //已收
        BIDReceivedMeetingCell *receivedMeetingCell = [tableView dequeueReusableCellWithIdentifier:received_identifier];
        NSNumber *isReadValue = dic[@"isRead"];
        NSString *strReadStatus = [isReadValue intValue]==1 ? @"已读" : @"未读";
        strReadStatus = [[NSString alloc] initWithFormat:@"[%@]", strReadStatus];
        NSMutableAttributedString *strAttribute = [[NSMutableAttributedString alloc] initWithString:[[NSString alloc] initWithFormat:@"%@ %@", strReadStatus, noticeDic[@"title"]]];
        if([isReadValue intValue] == 1)
        {
            //已读
            [strAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, strReadStatus.length)];
        }
        else
        {
            //未读
            [strAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, strReadStatus.length)];
        }
        receivedMeetingCell.titleLabel.attributedText = strAttribute;
        receivedMeetingCell.timeLabel.text = noticeDic[@"createTime"];
        receivedMeetingCell.nameLabel.text = [[NSString alloc] initWithFormat:@"发送人:%@", noticeDic[@"createUserName"]];
        cell = receivedMeetingCell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    NSDictionary *dic = self.dataSourceArr[row];
    BIDMeetingDetailViewController *vc = [[BIDMeetingDetailViewController alloc] initWithNibName:@"BIDMeetingDetailViewController" bundle:nil];
    vc.isSent = _isSent;
    vc.meetingID = dic[@"id"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return _isSent ? 50.f : 85.f;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        //删除某条会议
        [self deleteMeetingAtIndexPath:indexPath];
    }
}

@end
